<script setup lang="ts">
// 在 setup() 作用域中执行 (对每个实例皆如此)
import { reactive, toRefs, ref } from 'vue'
import { Icon } from '@/components/SvgIcon';
import AppLogo from '@/layout/components/Logo.vue'
import { useI18n } from '@/hooks/web/useI18n';
import Schema, { Rules } from 'async-validator'

import { useStore } from '@/store'

import { ElMessage, ElNotification } from 'element-plus'

import { getCodeImage } from '@/api/auth'

import { useRouter, useRoute } from 'vue-router'
import { LoginParam } from '@/api/authModel';

// 预加载区......start
getVerificationCode()
// 预加载区......end
// 变量区
const store = useStore()
const router = useRouter()
const route = useRoute()
const { t } = useI18n()

const loginParam = ref<LoginParam>({
  uuid: '',
  usernameOrPhone: 'admin',
  password: '123456',
  verificationCode: '',
  remberMe: false
})

const data = reactive({
  inputSvg: {
    width: '20px',
    height: '20px'
  },
  isLoading: false,
  loginRules: {
    usernameOrPhone: [
      {
        required: true,
        message: '请输入用户名或者电话号码',
        trigger: 'blur'
      },
      {
        min: 5,
        max: 30,
        message: '长度在5到30',
        trigger: 'blur'
      }
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur'
      },
      {
        min: 6,
        max: 30,
        message: '长度在6到30',
        trigger: 'blur'
      }
    ],
    verificationCode: [
      {
        required: true,
        message: '请输入验证码',
        trigger: 'blur'
      }
    ]
  }
})
const { loginRules, isLoading } = toRefs(data)
const codeUrl = ref('')

// 变量区....end

// 表单验证......start
const descriptor: Rules = {
  usernameOrPhone: {
    type: 'string',
    required: true,
    message: '用户名不能为空'
  },
  password: {
    type: 'string',
    required: true,
    message: '密码不能为空'
  },
  verificationCode: [
    {
      type: 'string',
      required: true,
      message: '验证码不能为空'
    }
  ]
}
const validator = new Schema(descriptor)

// 表单验证结束

// methods 方法区
// 获取验证码
async function getVerificationCode() {
  let res = await getCodeImage()
  codeUrl.value = res.img
  loginParam.value.uuid = res.uuid
}
// 登录
function handleLogin() {
  isLoading.value = true
  validator
    .validate(loginParam.value)
    .then(() => {
      store
        .dispatch('login', loginParam.value)
        .then(() => {
          console.log('登录成功')
          const isLogin = router
            .push({ path: route.redirectedFrom?.path || '/', replace: true })
            .catch(err => {
              console.log(err)
            })

          isLogin.then(() => {
            isLoading.value = false
            ElNotification.success({
              message: '登录成功',
              duration: 3000,
              type: 'success',
            })
          })
        })
        .catch(() => {
          restForm()
          isLoading.value = false
        })
    })
    .catch(({ errors, fields }) => {
      isLoading.value = false
      ElMessage({
        showClose: true,
        message: errors[0].message,
        type: 'error',
        duration: 3000
      })
    })
}

function clearCode() {
  loginParam.value.verificationCode = ''
}
// 重置表单数据
function restForm() {
  // loginParam.value.usernameOrPhone = ''
  // loginParam.value.password = ''
  // loginParam.value.uuid = ''
  // loginParam.value.verificationCode = ''
  getVerificationCode()
}

// 方法区......end
</script>

<script lang="ts">
import { defineComponent } from 'vue';
// 普通 <script>, 在模块范围下执行(只执行一次)
export default defineComponent({
  // 已启用类型推断

  data() {
    return {}
  },
  methods: {
    //  登录表单回车获取焦点
    focusNext(nextRef: string) {
      (this.$refs[nextRef] as any).focus()
    }
  }
})
</script>

<template>
  <div class="gm-login">
    <div class="left-container">
      <AppLogo :collapse="false" />
      <div class="left-content">
        <img alt="火箭发射" src="@/assets/images/bg-rocket.svg" class />
        <div class="font-medium text-white ">
          <span class="inline-block mt-4 text-3xl">{{ '欢迎使用GM' }}</span>
        </div>
      </div>
    </div>
    <el-container>
      <el-main>
        <el-form ref="loginForm" :model="loginParam" label-width="0px" :rules="loginRules" :statusIcon="true">
          <h2 style="color: black">登录</h2>
          <el-form-item prop="usernameOrPhone">
            <el-input v-model="loginParam.usernameOrPhone" text placeholder="用户名或邮箱或电话" autofocus clearable size="large"
              @keyup.enter="focusNext('password')">
              <template #prefix>
                <!-- <Icon icon="user-filled|svg" color="#1296db" /> -->
                <svg-icon icon-class="user" class="el-input__icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input ref="password" v-model="loginParam.password" type="password" placeholder="密码" show-password
              clearable size="large" @keyup.enter="focusNext('verificationCode')">
              <template #prefix>
                <svg-icon icon-class="password" class="el-input__icon" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="verificationCode">
            <el-input ref="verificationCode" text v-model="loginParam.verificationCode" auto-complete="off"
              placeholder="验证码" style="width: 50%; float: left" clearable size="large" @keyup.enter="handleLogin">
              <template #prefix>
                <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
              </template>
            </el-input>
            <div @click="getVerificationCode">
              <el-image :src="codeUrl" @load="clearCode" @error="clearCode">
                <template #placeholder>
                  <div class="image-slot">
                    Loading
                    <span class="dot">...</span>
                  </div>
                </template>
                <template #error>
                  <div class="image-slot">
                    <svg-icon icon-class="image-fail" />
                  </div>
                </template>
              </el-image>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="isLoading" round style="min-width: -webkit-fill-available"
              auto-insert-space @click.enter.prevent="handleLogin">登录</el-button>
          </el-form-item>
          <div class="remberAndForgetPasswd">
            <el-checkbox v-model="loginParam.remberMe" label="记住我" size="small" class="custom-class"></el-checkbox>
            <el-button-group>
              <el-button text style="margin-right: 10px">忘记密码</el-button>
              <el-button text>新用户注册</el-button>
            </el-button-group>
          </div>
        </el-form>
      </el-main>
      <el-footer></el-footer>
    </el-container>
  </div>
</template>


<style lang="scss" scoped>
.el-main {
  //   background-color: #fdf9f271;
  min-height: calc(100vh - 120px);
  text-align: -webkit-center;
  display: flex;
  align-content: space-around;
  flex-direction: row;
  padding: 0;
  flex-wrap: wrap;
  margin-left: 10%;
  justify-content: center;

  .el-form {
    width: 400px;
    z-index: 0;
    padding: 50px;
    // background-color: #26577f;
    // opacity: 0.9;
    border-radius: 10px;
    margin-left: 20%;

    .el-form-item {
      width: 350px;
    }

    :deep(.el-form-item__content) {
      display: flex;
      flex-direction: row;
      align-content: center;
      justify-content: space-between;
      align-items: flex-start;
    }

    :deep(.el-input__prefix-inner) {
      align-items: center;
    }
  }

  .remberAndForgetPasswd {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    align-items: center;

    .custom-class {
      color: rgb(12, 12, 12);
      --el-checkbox-font-size: 12px;
    }
  }

  .el-image {
    min-width: 35%;
    max-height: 100%;
    background-color: white;
    opacity: 0.5;

    img {
      width: 100%;
    }
  }
}

.gm-login::before {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin-left: -48%;
  background-image: url(@/assets/images/login-bg.svg);
  background-position: 100%;
  background-repeat: no-repeat;
  background-size: auto 100%;
  content: "";
}

.left-container {
  display: flex;
  position: fixed;
  top: 10%;
  left: 0;
  bottom: 10%;
  right: 60%;
  flex-direction: column;

  & .left-content {
    margin-top: 20px;
  }
}
</style>

